<?php

class UserController extends Controller
{

	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}

	
	public function accessRules()
	{
		return array(
				array('allow',  // allow all users to perform 'index' and 'view' actions
						'actions'=>array('index', 'view', 'create'),
						'roles'=>array('admin'),
						'users'=>array('@'),
				),
				array('allow',
						'actions'=>array('update', 'delete'),
						'users'=>array('admin'),
						'roles'=>array('admin')
				),
				array('deny',  // deny all users
						'users'=>array('*')
				)
		);
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;

		$projectListData = CHtml::listData(Project::model()->findAll(),'projectId','projectName');
		$hostListData = CHtml::listData(Host::model()->findAll(),'hostId','hostText', 'hostType');
		$prodHostListData = isset($hostListData[1]) ? $hostListData[1] : array(); //生产主机
		$testHostListData = isset($hostListData[0]) ? $hostListData[0] : array(); //测试主机
		
		$userProjectIds = array();	//用户项目ID列表
		$userTestHostIds = array();
		$userProdHostIds = array();

		if(isset($_POST['User']))
		{
			
			$model->attributes=$_POST['User'];

			if($model->validate()) {
				$model->password = md5($model->password);
				$model->save(false);
				$userProjectIds = isset($_POST['userProjectIds'])?$_POST['userProjectIds']: array();
				if (is_array($userProjectIds) && count($userProjectIds)>0) {
					$sql = "INSERT INTO {{project_user}} (projectId, userId) VALUES ";
					foreach($userProjectIds as $userProjectId) {
						 $sql .= " ($userProjectId, $model->userId),";
					}
					$sql = rtrim($sql, ",");
					Yii::app()->db->createCommand($sql)->execute();
				}
				
				//主机列表
				$userProdHostIds = isset($_POST['userProdHostIds']) ? $_POST['userProdHostIds'] : array();
				$userTestHostIds = isset($_POST['userTestHostIds']) ? $_POST['userTestHostIds'] : array();
				$userHostIds = array_merge($userProdHostIds, $userTestHostIds);
				if (is_array($userHostIds) && count($userHostIds)>0) {
					$sql = "INSERT INTO {{user_host}} (userId, hostId) VALUES ";
					foreach($userHostIds as $userHostId) {
						$sql .= " ($model->userId, $userHostId),";
					}
					$sql = trim($sql, ",");
					Yii::app()->db->createCommand($sql)->execute();
				}
				
				$this->redirect(array('view','id'=>$model->userId));
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'projectListData'=>$projectListData,
			'prodHostListData'=>$prodHostListData,
		    'testHostListData'=>$testHostListData,
			'userProjectIds'=>$userProjectIds,
		    'userTestHostIds'=>$userTestHostIds,
		    'userProdHostIds'=>$userProdHostIds
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		
		//用户项目ID列表
		$userProjectIds = Yii::app()->db->createCommand()
								->from('{{project_user}}')
								->select('projectId')
								->where('userId=?')
								->queryColumn(array($id));
		if (is_null($userProjectIds)) $userProjectIds = array();	
		
		//用户测试主机ID列表
		$userTestHostIds = Yii::app()->db->createCommand()
								->from('{{user_host}} t')
								->select('t.hostId')
								->join('{{host}} h', 't.hostId=h.hostId AND hostType=0')
								->where('userId=?')
								->queryColumn(array($id));
		if (is_null($userTestHostIds)) $userTestHostIds = array();
		
		//用户产生主机ID列表
		$userProdHostIds = Yii::app()->db->createCommand()
								->from('{{user_host}} t')
								->select('t.hostId')
								->join('{{host}} h', 't.hostId=h.hostId AND hostType=1')
								->where('userId=?')
								->queryColumn(array($id));
		if (is_null($userProdHostIds)) $userProdHostIds = array();
		
		
		$projectListData = CHtml::listData(Project::model()->findAll(),'projectId','projectName');
		$hostListData = CHtml::listData(Host::model()->findAll(),'hostId','hostText', 'hostType');
		$prodHostListData = isset($hostListData[1]) ? $hostListData[1] : array(); //生产主机
		$testHostListData = isset($hostListData[0]) ? $hostListData[0] : array(); //测试主机

		if(isset($_POST['User']))
		{
			$oldPassword = $model->password;
			$model->attributes=$_POST['User'];
			
			if ($model->validate()) {
				if ($model->password=='' || $oldPassword==$model->password) $model->password=$oldPassword;
				else $model->password=md5($model->password);
				$model->save(false);
				$userProjectIds = isset($_POST['userProjectIds'])?$_POST['userProjectIds']: array();

				//$model->save()
				//项目列表
				$sql = "DELETE FROM {{project_user}} WHERE userId=?";
				Yii::app()->db->createCommand($sql)->execute(array($model->userId));
				if (is_array($userProjectIds) && count($userProjectIds)>0) {
					$sql = "INSERT INTO {{project_user}} (projectId, userId) VALUES ";
					foreach($userProjectIds as $userProjectId) {
						 $sql .= " ($userProjectId, $model->userId),";
					}
					$sql = rtrim($sql, ",");
					
					Yii::app()->db->createCommand($sql)->execute();
				}
				
				//主机列表
				$userProdHostIds = isset($_POST['userProdHostIds']) ? $_POST['userProdHostIds'] : array();
				$userTestHostIds = isset($_POST['userTestHostIds']) ? $_POST['userTestHostIds'] : array();
				$userHostIds = array_merge($userProdHostIds, $userTestHostIds);
				$sql = "DELETE FROM {{user_host}} WHERE userId=?";
				Yii::app()->db->createCommand($sql)->execute(array($model->userId));
				if (is_array($userHostIds) && count($userHostIds)>0) {
					$sql = "INSERT INTO {{user_host}} (userId, hostId) VALUES ";
					foreach($userHostIds as $userHostId) {
						$sql .= " ($model->userId, $userHostId),";
					}
					$sql = trim($sql, ",");
					Yii::app()->db->createCommand($sql)->execute();
				}
				
				$this->redirect(array('view','id'=>$model->userId));
			}
		}

		$model->password='';
		$this->render('update',array(
			'model'=>$model,
			'projectListData'=>$projectListData,
			'prodHostListData'=>$prodHostListData,
		    'testHostListData'=>$testHostListData,
			'userProjectIds'=>$userProjectIds,
		    'userTestHostIds'=>$userTestHostIds,
		    'userProdHostIds'=>$userProdHostIds
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			$model = $this->loadModel($id);
			if ($model->username==Yii::app()->user->name) 
				throw new CHttpException('403', '不能删除自己');
			if ($model->username=='admin')
				throw new CHttpException('403', 'Admin用户不能删除');
			// we only allow deletion via POST request
			$model->delete();
			
			$sql = "DELETE FROM {{project_user}} WHERE userId=?";
			Yii::app()->db->createCommand($sql)->execute(array($id));
			
			$sql = "DELETE FROM {{user_host}} WHERE userId=?";
			Yii::app()->db->createCommand($sql)->execute(array($id));
			
			$sql = "DELETE FROM {{user_tag}} WHERE userId=?";
			Yii::app()->db->createCommand($sql)->execute(array($id));

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('index',array(
			'model'=>$model,
		));
	}


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
